﻿CREATE PROCEDURE [audit].[Refresh]
@RestartTrace BIT=1
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int
	SET @RC = 0

	DECLARE TRACES_CURSOR CURSOR READ_ONLY FOR(
		SELECT [TraceName]
		FROM [config].[TraceDefinitions]
		WHERE  ([TraceName] LIKE N'%Audit%')
			AND([Enabled] = 1)
		GROUP BY [TraceName]
	)
	OPEN TRACES_CURSOR
	PRINT N'There are '
		+ CAST(@@CURSOR_ROWS AS nvarchar)
		+ N' trace(s) configured and enabled.'
	IF(@@CURSOR_ROWS = 0)
		GOTO EXIT_CURSOR

	DECLARE @TraceName nvarchar(256)
	FETCH NEXT FROM TRACES_CURSOR INTO @TraceName
	WHILE(@@FETCH_STATUS = 0)
		BEGIN
			DECLARE @TracePath nvarchar(512)

			EXEC @RC = audit.StopTrace @TraceName, @TracePath OUTPUT
			IF(@@ERROR <> 0)
			OR(@RC <> 0)
			OR(@TracePath IS NULL)
				GOTO START_TRACE

			EXEC @RC = audit.LoadTraceData @TraceName, @TracePath
			IF(@@ERROR <> 0)
			OR(@RC <> 0)
				GOTO START_TRACE

			EXEC @RC = audit.DeleteTraceFiles @TracePath
			IF(@@ERROR <> 0)
			OR(@RC <> 0)
				GOTO START_TRACE

START_TRACE:
			IF(@RestartTrace = 0)
				GOTO EXIT_CURSOR

			DECLARE @TraceID int

			EXEC @RC = audit.InitialiseTrace @TraceName, @TraceID OUTPUT
			IF(@@ERROR <> 0)
			OR(@RC <> 0)
				GOTO EXIT_CURSOR

			EXEC @RC = audit.DefineTrace @TraceName, @TraceID
			IF(@@ERROR <> 0)
			OR(@RC <> 0)
				GOTO EXIT_CURSOR

			EXEC @RC = audit.StartTrace @TraceID
			IF(@@ERROR <> 0)
			OR(@RC <> 0)
				GOTO EXIT_CURSOR

			FETCH NEXT FROM TRACES_CURSOR INTO @TraceName
		END
EXIT_CURSOR:
	CLOSE TRACES_CURSOR
	DEALLOCATE TRACES_CURSOR

EXIT_PROC:
	RETURN(@RC)
END